package com.zhentao.datacontrol.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhentao.datacontrol.domain.dto.DataControlRuleDTO;
import com.zhentao.datacontrol.service.DataControlRuleService;
import com.zhentao.subscription.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/datacontrol/rules")
@CrossOrigin(origins = "*")
public class DataControlRuleController {

    @Autowired
    private DataControlRuleService ruleService;

    /**
     * 分页查询规则列表
     */
    @GetMapping
    public R<IPage<DataControlRuleDTO>> getRulePage(
            @RequestParam(defaultValue = "1") int pageNo,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) Long groupId,
            @RequestParam(required = false) String ruleName,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String publishStatus) {

        try {
            IPage<DataControlRuleDTO> page = ruleService.getRulePage(pageNo, pageSize, groupId, ruleName, status, publishStatus);
            return R.ok(page);
        } catch (Exception e) {
            // 如果数据库表不存在，返回空页面而不是500错误
            System.err.println("DataControl rules query failed: " + e.getMessage());
            IPage<DataControlRuleDTO> emptyPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNo, pageSize, 0);
            return R.ok(emptyPage);
        }
    }

    /**
     * 获取规则详情
     */
    @GetMapping("/{id}")
    public R<DataControlRuleDTO> getRuleDetail(@PathVariable Long id) {
        DataControlRuleDTO rule = ruleService.getRuleDetail(id);
        if (rule == null) {
            return R.error("规则不存在");
        }
        return R.ok(rule);
    }

    /**
     * 创建规则
     */
    @PostMapping
    public R<Long> createRule(@Valid @RequestBody DataControlRuleDTO ruleDTO) {
        try {
            Long id = ruleService.createRule(ruleDTO);
            return R.ok(id);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 更新规则
     */
    @PutMapping("/{id}")
    public R<Void> updateRule(@PathVariable Long id, @Valid @RequestBody DataControlRuleDTO ruleDTO) {
        try {
            ruleDTO.setId(id);
            boolean success = ruleService.updateRule(ruleDTO);
            return success ? R.ok() : R.error("更新失败");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 删除规则
     */
    @DeleteMapping("/{id}")
    public R<Void> deleteRule(@PathVariable Long id) {
        try {
            boolean success = ruleService.deleteRule(id);
            return success ? R.ok() : R.error("删除失败");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 发布规则
     */
    @PostMapping("/{id}/publish")
    public R<Void> publishRule(@PathVariable Long id) {
        try {
            boolean success = ruleService.publishRule(id);
            return success ? R.ok() : R.error("发布失败");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 取消发布规则
     */
    @PostMapping("/{id}/unpublish")
    public R<Void> unpublishRule(@PathVariable Long id) {
        try {
            boolean success = ruleService.unpublishRule(id);
            return success ? R.ok() : R.error("取消发布失败");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 启用规则
     */
    @PostMapping("/{id}/enable")
    public R<Void> enableRule(@PathVariable Long id) {
        try {
            boolean success = ruleService.enableRule(id);
            return success ? R.ok() : R.error("启用失败");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 禁用规则
     */
    @PostMapping("/{id}/disable")
    public R<Void> disableRule(@PathVariable Long id) {
        try {
            boolean success = ruleService.disableRule(id);
            return success ? R.ok() : R.error("禁用失败");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 移动规则到指定分组
     */
    @PostMapping("/{id}/move")
    public R<Void> moveRuleToGroup(@PathVariable Long id, @RequestParam Long groupId) {
        try {
            boolean success = ruleService.moveRuleToGroup(id, groupId);
            return success ? R.ok() : R.error("移动失败");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 获取分组下的规则列表
     */
    @GetMapping("/group/{groupId}")
    public R<List<DataControlRuleDTO>> getRulesByGroup(@PathVariable Long groupId) {
        List<DataControlRuleDTO> rules = ruleService.getRulesByGroup(groupId);
        return R.ok(rules);
    }

    /**
     * 获取规则树形结构
     */
    @GetMapping("/tree")
    public R<List<DataControlRuleDTO>> getRuleTree() {
        List<DataControlRuleDTO> tree = ruleService.getRuleTree();
        return R.ok(tree);
    }

    /**
     * 检查规则编码是否存在
     */
    @GetMapping("/check-code")
    public R<Boolean> checkRuleCodeExists(@RequestParam String ruleCode, 
                                        @RequestParam(required = false) Long excludeId) {
        boolean exists = ruleService.checkRuleCodeExists(ruleCode, excludeId);
        return R.ok(exists);
    }

    /**
     * 生成下一个规则编码
     */
    @GetMapping("/next-code")
    public R<String> generateNextRuleCode() {
        String code = ruleService.generateNextRuleCode();
        return R.ok(code);
    }

    /**
     * 获取已发布的规则列表
     */
    @GetMapping("/published")
    public R<List<DataControlRuleDTO>> getPublishedRules() {
        List<DataControlRuleDTO> rules = ruleService.getPublishedRules();
        return R.ok(rules);
    }

    /**
     * 复制规则
     */
    @PostMapping("/{id}/copy")
    public R<Long> copyRule(@PathVariable Long id, @RequestParam String newRuleName) {
        try {
            Long newId = ruleService.copyRule(id, newRuleName);
            return R.ok(newId);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 批量更新排序
     */
    @PostMapping("/sort")
    public R<Void> updateSortOrders(@RequestBody SortOrderRequest request) {
        try {
            boolean success = ruleService.updateSortOrders(request.getIds(), request.getSortOrders());
            return success ? R.ok() : R.error("排序更新失败");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 排序请求对象
     */
    public static class SortOrderRequest {
        private List<Long> ids;
        private List<Integer> sortOrders;

        public List<Long> getIds() { return ids; }
        public void setIds(List<Long> ids) { this.ids = ids; }

        public List<Integer> getSortOrders() { return sortOrders; }
        public void setSortOrders(List<Integer> sortOrders) { this.sortOrders = sortOrders; }
    }
}
